package com.tinem.platform.service.security.observable;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className ImageApi
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-28 10:08
 */
@Service
public class ImageListener implements ApplicationListener<GenerateObservable> {

    @Value("${verification.code.image.effective-time}")
    Duration imageCodeEffectiveTime;

    @Override
    public void onApplicationEvent(GenerateObservable event) {
        if(!StrUtil.equalsAny(event.getChannel(), "image")){
            return;
        }
        AbstractCaptcha captcha = null;
        switch (event.getSource().getInterferenceType()){
            case Line:
                captcha = CaptchaUtil.createLineCaptcha(
                        event.getSource().getWidth(),
                        event.getSource().getHeight(),
                        event.getSource().getCodeCount(),
                        event.getSource().getInterferenceLevel());
                break;
            case Shear:
                captcha = CaptchaUtil.createShearCaptcha(
                        event.getSource().getWidth(),
                        event.getSource().getHeight(),
                        event.getSource().getCodeCount(),
                        event.getSource().getInterferenceLevel());
                break;
            case Circle:
                captcha = CaptchaUtil.createCircleCaptcha(
                        event.getSource().getWidth(),
                        event.getSource().getHeight(),
                        event.getSource().getCodeCount(),
                        event.getSource().getInterferenceLevel());
                break;
            default: break;
        }
        event.setCode(captcha.getCode());
        event.setImageBase64(captcha.getImageBase64());
        event.setCodeEffectiveTime(imageCodeEffectiveTime);
    }
}
